import socket
import os
import sys
import struct
import json
def download(sk):
    opt_dic={'operate':'download'}
    my_send(sk,opt_dic)
    msg=my_recv(sk)
    with open(msg['filename'], mode='wb') as f:
        while msg['filesize'] > 0:
            content = sk.recv(1024)
            msg['filesize'] -= len(content)
            f.write(content)


def my_recv(sk):
    msg_len=sk.recv(4)
    dic_len=struct.unpack('i',msg_len)[0]
    msg=sk.recv(dic_len).decode('utf-8')
    msg=json.loads(msg)
    return msg


def my_send(sk,dic):
    str_dic=json.dumps(dic)
    b_dic=str_dic.encode('utf-8')
    mlen=struct.pack('i',len(b_dic))
    sk.send(mlen)
    sk.send(b_dic)


def login(sk):
    while True:
        # 登录
        user = input('用户名：').strip()
        pwd = input('密码 ：').strip()
        dic = {'username': user, 'password': pwd}
        my_send(sk, dic)
        ret = my_recv(sk)
        if ret['operate'] == 'login' and ret['result']:
            print('登录成功')
            break
        else:
            print('登陆失败')


sk = socket.socket()

sk.connect(('127.0.0.1', 9001))
login(sk)
#上传/下载
opt_list=['upload','download']
for index,opt in enumerate(opt_list,1):
    print(index,opt)

num=int(input('请选择你要操作的序号'))
getattr(sys.modules[__name__],opt_list[num-1])(sk)


sk.close()


























